package com.example.shell.util;

public class XOREncryption {
    public static void main(String[] args) {
        String plaintext = "password"; // 明文
        String key = "ENLON"; // 加密密钥

        String ciphertext = encrypt(plaintext, key);
        System.out.println("密文: " + ciphertext);
        String decrypt = decrypt(ciphertext, key);
        System.out.println("明文: " + decrypt);
    }

    public static String encrypt(String plaintext, String key) {
        byte[] textBytes = plaintext.getBytes();
        byte[] keyBytes = key.getBytes();
        byte[] encryptedBytes = new byte[textBytes.length];

        for (int i = 0; i < textBytes.length; i++) {
            encryptedBytes[i] = (byte) (textBytes[i] ^ keyBytes[i % keyBytes.length]);
        }

        return bytesToHex(encryptedBytes);
    }

    public static String decrypt(String hexCiphertext, String key) {
        byte[] ciphertext = hexToBytes(hexCiphertext);
        byte[] keyBytes = key.getBytes();
        byte[] decryptedBytes = new byte[ciphertext.length];

        for (int i = 0; i < ciphertext.length; i++) {
            decryptedBytes[i] = (byte) (ciphertext[i] ^ keyBytes[i % keyBytes.length]);
        }

        return new String(decryptedBytes);
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    public static byte[] hexToBytes(String hex) {
        int length = hex.length();
        byte[] data = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }
}
